'use strict'

const http = require('http')
/*
.jpg .jpeg ->  image/jpeg
.png       ->  image/png
.gif       ->  image/gif
.ico       ->  image/x-icon
.txt       ->  image/plain
.json      ->  text/json 或 application/json
.xml       ->  text/xml  或 application/xml
*/
let html = `
    <!DOCTYPE html>
    <html>
        <head>
            <title>First HTTP</title>
        </head>
        <body>
            你好。
        </body>
    </html>
`

let routerTable = {
    '/': async (request, response) => {
        response.setHeader('content-type', 'text/html; charset=utf-8')
        response.end(html)
    },
    '/test':async (request,response)=>{
        let status = parseInt(Math.random()*200)+199
        response.statusCode=status
        response.end('test end')
    },
    '/data': async (request, response) => {
        let bufferList = []
        let bufferLength = 0

        request.on('data', chunk => {//只要数据还在传输就一直触发data事件，跟微信小程序里的‘data’不一样，那里面的只是个参数
            bufferLength += chunk.length
            bufferList.push(chunk)
        })
        let bodyData = null
        request.on('end', () => {//数据传入完成后触发end事件
            if (bufferList.length > 0) {
                bodyData = Buffer.concat(bufferList, bufferLength)//返回一个连接了list中所有Buffer的新Buffer  返回：{Buffer}
                bufferList = []
            }
            //----------打印文件信息--------//
            let file=parseBody(bodyData,request.headers)
            console.log(file)

            if (bodyData) {
                response.end(bodyData)
            } else {
                response.end()
            }
        })
        // response.setHeader('content-type', 'text/plain; charset=utf-8')//会认为是txt格式，就不会按照html格式进行解析了
    }
}

http.createServer((request, response) => {
    if (!routerTable[request.url]) {
        response.statusCode = 404
        response.end('page not found')
        return
    }
    routerTable[request.url](request, response) //调用routerTable中的某个方法，为该方法传参
}).listen(3456)